﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using AForge.Video.FFMPEG;
using FingerTracking;
using Microsoft.Kinect;
using fingerWinForm.DataBase;
using fingerWinForm.GUI;
using fingerWinForm.SVM;
using fingerWinForm.UpdrsTests;
using fingerWinForm.Excel;
using fingerWinForm.Algorithms.SVM;

using fingerWinForm.Utilities;

namespace fingerWinForm
{
    public struct TrainingModetestGrades
    {
        public string RfingerTaps;
        public string RhandMovments;
        public string LfingerTaps;
        public string LhandMovments;
    }

    public enum Mode
    {
        TRAINING_MODE = 0,
        TESTING_MODE = 1
    }

    public enum HandSide
    {
        LEFT = 0,
        RIGHT = 1
    }


    public partial class MainWindow : Form
    {
        KinectTracker kinectController;
        FileMgr excelManeger;
        private RecordingManager recordingManager;
        private List<int> testsList;
        private int testsListIndex;
        public string timeComposer; //used for the name of the file when it is saved
        private Dictionary<int, string> modelsPath;
        private String modelPathString;
        private int numOfTestsPerformed;

        public enum TestName
        {
            FINGER_TAPS = 23,
            HAND_MOVEMENTS = 24
        }

        public struct InfoForPredict
        {
            public string testFilePath;
            public string modelFilePath;
            public string outputFilePath;
            public FileMgr FileMgr;
        }

        static public string startingPath = @"C:\parkinsonTool\";
        static public Mode systemMode = Mode.TESTING_MODE;
        static public TrainingModetestGrades trainingGrades;

        public MainWindow(ref FileMgr passedExcelManegerpassed)
        {
            InitializeComponent();
            createObjects(ref passedExcelManegerpassed); 
            objectsSettings();
            excelManeger.eTrainFileWasCreated += new FileMgr.trainFileWasCreated(runSvmPredict);
            
            
        }

        private void createObjects(ref FileMgr passedExcelManeger)
        {
            kinectController = new KinectTracker();
            excelManeger = passedExcelManeger;
            recordingManager = new RecordingManager();
            trainingGrades = new TrainingModetestGrades();
            testsList = new List<int>();
            modelsPath = new Dictionary<int, string>();
            modelPathString = "";
            numOfTestsPerformed = 0;

        }

        private void objectsSettings()
        {

            recordingButton.Enabled = false;
            saveAsMovieCheckBox.Enabled = false;
            testsListIndex = 0;
            if (Users.userRole != "Administrator")
            {
                manageUsersToolStripMenuItem.Visible = false;
                SVMToolStripMenuItem.Visible = false;
                trainingModeTab.Enabled = false;
            }
        }

        private void drawDepthImage()
        {


            // After the depth image is ready and the tracking done
            KinectTracker.afterReady a = drawDepthImage; // Show the depth image
            a = a + showNumberFingers; // Show the number of fingers
            kinectController.setEventDepthReady(a);
            setImageInsteadOfKinect();

        }

        private void setImageInsteadOfKinect()
        {
            if (startKinectButton.Enabled == false || startKinectButton.Text == "Start Kinect")
            {
                trackingImage.Image = (Image) Properties.Resources.ResourceManager.GetObject("Pic1");
            }
            else
            {
                trackingImage.Image = kinectController.getDepthImage();    
            }
        }

        private void showNumberFingers()
        {

        }

        private void addNewPatientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addNewPatientWindow addNewPatientWindow = new addNewPatientWindow(excelManeger);
            addNewPatientWindow.StartPosition = this.StartPosition;
            addNewPatientWindow.ShowDialog();

        }

        private void startKinectButton_Click(object sender, EventArgs e)
        {
            do
            {
                if (startKinectButton.Text == "Start Kinect")
                {
                    if (kinectController.isConnected())
                    {
                        if (kinectController.start())
                        {
                            recordingButton.Enabled = true;
                            saveAsMovieCheckBox.Enabled = true;
                            startKinectButton.Text = "Stop Kinect";
                            kinectController.setEventDepthReady(drawDepthImage);
                            if (systemMode == Mode.TRAINING_MODE && testsList.Count != 0)
                            {
                                String text = "You have " + testsList.Count.ToString() + " tests to perform";
                                MessageBox.Show(text, "TRAINING MODE", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                recordingManager.showNextTestOnLabel(this, testsList[0], kinectController, HandSide.LEFT);
                            }
                            else if (systemMode == Mode.TESTING_MODE)
                            {
                                String text = "You have " + testsList.Count.ToString() + " tests to perform";
                                MessageBox.Show(text, "TESTING MODE", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                recordingManager.showNextTestOnLabel(this, testsList[0], kinectController, HandSide.LEFT);
                            }
                            recordingsPanel.Visible = true;
                        }
    
                    }
                    else
                    {
                        // Show an error
                        String text = "There is not any Kinect device connected.\nConnect it and restart the application.\n";
                        if (systemMode == Mode.TRAINING_MODE)
                        {
                            MessageBox.Show(text, "TRAINING MODE", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show(text, "TESTING MODE", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    break;
                }
                else
                {
                    startKinectButton.Text = "Start Kinect";
                    recordingButton.Enabled = false;
                    saveAsMovieCheckBox.Enabled = false;
                    setImageInsteadOfKinect();
                    kinectController.stop();
                    clearTestButton.Enabled = true;
                    modelsPath.Clear();
                    startKinectButton.Enabled = false;
                    idUpperTextBox.Clear();
                    firstNameTextBox.Clear();
                    lastNameTextBox.Clear();
                    patientIDTextBox.Clear();
                    IDTextBox.Clear();
                    testsList.Clear();
                    recordingsPanel.Visible = false;
                }
                
            } while (false);
            
            
        }

        private void searchPatientButton_Click(object sender, EventArgs e)
        {
            if (CheckInput.isEmpty(patientIDTextBox.Text))
            {
                MessageBox.Show("Please enter patient ID", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if(!CheckInput.isNumber(patientIDTextBox.Text))
            {
                MessageBox.Show("ID must contains only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string patientId = patientIDTextBox.Text;
            PatientDetails patientDetails;
            patientDetails = excelManeger.findPatientDetails(patientId);
            if (patientDetails.id == null)
            {
                MessageBox.Show("This id was not found in the records", "My Application",
                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            idUpperTextBox.Text = patientDetails.id;
            firstNameTextBox.Text = patientDetails.firstName;
            lastNameTextBox.Text = patientDetails.lastName;
            if (startKinectButton.Text != "Stop Kinect")
                startTestsButton.Enabled = true;

        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (excelManeger != null)
            {
                excelManeger.closeFileMgr();
            }
                excelManeger = null; //free this manager
            
        }

        private void recordingButton_Click(object sender, EventArgs e)
        {
            bool rec;
            if (testsListIndex < testsList.Count)
            {
                do
                {
                    if (recordingButton.Text == "Start Recording")
                    {
                        numOfTestsPerformed++;
                        recordingButton.Text = "Stop Recording";
                        performingTestLabel.Visible = true;
                        string time = DateTime.Now.ToString("HHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                        string date = DateTime.Now.ToString("ddMMyyyy");
                        string dirpath;
                        string[] stringSliter = (instructionLabel2.Text.Substring(5)).Split(' ');
                        string nameOfTheTest = stringSliter[0] + " " +stringSliter[1];

                        if (systemMode == Mode.TRAINING_MODE)
                        {
                            timeComposer = IDTextBox.Text + "_" + date + "_" + time;
                            dirpath = startingPath + "rawData\\training\\" + nameOfTheTest + "\\" + IDTextBox.Text;    
                        }
                        else
                        {
                            timeComposer = idUpperTextBox.Text + "_" + date + "_" + time;
                            dirpath = startingPath + "rawData\\testing\\" + nameOfTheTest + "\\" + idUpperTextBox.Text;
                        }
                        
                        excelManeger.CreateIfMissing(dirpath);
                        if (saveAsMovieCheckBox.Checked)
                        {
                            rec = kinectController.startRecordingVideo(dirpath, this.timeComposer);
                            if (rec)
                            {
                                saveAsMovieCheckBox.Enabled = false;
                                kinectController.recordVideo = true;
                                kinectController.startRecordingRawData(stopWatchLabel, this.timeComposer);
                                instructionLabel1.Text = "Click on \"Stop Recording\" button for stopping test:";
                                recordingManager.startRecording(kinectController, this, testsList[testsListIndex], this.timeComposer);
                                break;

                            }
                        }
                        instructionLabel1.Text = "Click on \"Stop Recording\" button for stopping test:";
                        recordingManager.startRecording(kinectController, this, testsList[testsListIndex], this.timeComposer);

                        break;
                    }
                    if (recordingButton.Text == "Stop Recording")
                    {
                        if (MainWindow.systemMode == Mode.TRAINING_MODE)//TRAINING_MODE
                        {
                            kinectController.stopRecordingRawData(excelManeger, this.IDTextBox.Text);
                        }
                        else if (MainWindow.systemMode == Mode.TESTING_MODE)//TESTING_MODE
                        {
                            kinectController.stopRecordingRawData(excelManeger, this.patientIDTextBox.Text);
                        }

                        if (saveAsMovieCheckBox.Checked)
                        {
                            kinectController.writer.Close();
                            //MessageBox.Show(this, "Video file was saved", "Message", MessageBoxButtons.OK,
                            //             MessageBoxIcon.Information);

                        }
                        HandSide handSide;
                        if (numOfTestsPerformed < (testsList.Count/2) )
                        {
                            handSide = HandSide.LEFT;
                        }
                        else
                        {
                            handSide = HandSide.RIGHT;
                        }
                        recordingButton.Text = "Start Recording";
                        instructionLabel1.Text = "Click on \"Start Recording\" button for starting test:";
                        testsListIndex++;
                        if (testsListIndex < testsList.Count)
                        {
                            recordingManager.showNextTestOnLabel(this, testsList[testsListIndex], kinectController,handSide);
                        }
                        saveAsMovieCheckBox.Enabled = true;
                        performingTestLabel.Visible = false;
                        
                        if (systemMode == Mode.TESTING_MODE)
                        {
                            if (upperTestNameLabel.Text.Contains("23 - Finger Taps"))
                            {
                                modelsPath.TryGetValue(23, out modelPathString);
                            }
                            else if (upperTestNameLabel.Text.Contains("24 - Hand Movements"))
                            {
                                modelsPath.TryGetValue(24, out modelPathString);
                            }
                        }
                        upperTestNameLabel.Text = "";
                    }

                } while (false);

            }
            if (testsListIndex == testsList.Count)
            {
                if (systemMode == Mode.TRAINING_MODE)
                {
                    recordingsPanel.Visible = false;
                    MessageBox.Show("Training is finished", "TRAINING MODE", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                    kinectController.stop();
                    startKinectButton.Text = "Start Kinect";
                    startKinectButton.Enabled = false;
                    trackingImage.Image = Properties.Resources.Pic1; 
                    startButton.Enabled = true;
                    clearButton.Enabled = true;
                    testsList.Clear();
                    testsListIndex = 0;
                    IDTextBox.Clear();
                    fingerTapsLeftTextBox.Clear();
                    fingerTapsRightTextBox.Clear();
                    handMovementsLeftTextBox.Clear();
                    handMovementsRightTextBox.Clear();
                    numOfTestsPerformed = 0;
                }
                else //systemMode == Mode.TESTING_MODE
                {
                    recordingsPanel.Visible = false;
                    MessageBox.Show("Testing is finished", "TESTING MODE", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                    kinectController.stop();
                    startKinectButton.Text = "Start Kinect";
                    startKinectButton.Enabled = false;
                    trackingImage.Image = Properties.Resources.Pic1;
                    startTestsButton.Enabled = true;
                    clearTestButton.Enabled = true;
                    testsList.Clear();
                    testsListIndex = 0;
                    patientIDTextBox.Clear();
                    idUpperTextBox.Clear();
                    firstNameTextBox.Clear();
                    lastNameTextBox.Clear();
                    modelsPath.Clear();
                }
                
            }
        }

        public void runSvmPredict(string trainPath)
        {
            InfoForPredict infoForPredict = new InfoForPredict();
            infoForPredict.testFilePath = trainPath;
            infoForPredict.modelFilePath = modelPathString;
            infoForPredict.outputFilePath = trainPath + ".out";
            infoForPredict.FileMgr = excelManeger;
            ParameterizedThreadStart threadStart = new ParameterizedThreadStart(SVMManager.runSVMPredict);
            threadStart(infoForPredict);
            //ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SVMManager.runSVMPredict), infoForPredict);
        }

        private bool checkExistingOfModelFiles()
        {
            StreamReader modelPathFile;
            if (File.Exists(startingPath + @"svm\finger Taps\" + "PathOfSVMModelFile.txt"))
            {
                modelPathFile = new StreamReader(startingPath + @"svm\finger Taps\" + "PathOfSVMModelFile.txt");
                String path = modelPathFile.ReadLine();
                modelsPath.Add(23, path);
                modelPathFile.Close();
            }
            else
            {
                MessageBox.Show(
                    "There is no model file for \"Finger Taps\" test.\nPlease create model file and try again","ERROR",MessageBoxButtons.OK,MessageBoxIcon.Error);
                modelsPath.Clear();
                return false;
            }
            if (File.Exists(startingPath + @"svm\hand Movements\" + "PathOfSVMModelFile.txt"))
            {
                modelPathFile = new StreamReader(startingPath + @"svm\hand Movements\" + "PathOfSVMModelFile.txt");
                String path = modelPathFile.ReadLine();
                modelsPath.Add(24, path);
                modelPathFile.Close();
            }
            else
            {
                MessageBox.Show(
                    "There is no model file for \"Hand Movements\" test.\nPlease create model file and try again", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                modelsPath.Clear();
                return false;
            }
            return true;
        }

        private void enterToTrainingMode(object sender, EventArgs e)
        {
            systemMode = Mode.TRAINING_MODE;
            patientIDUpperLabel.Text = "";
            idUpperTextBox.BorderStyle = BorderStyle.None;
            idUpperTextBox.Clear();
            firstNameUpperLabel.Text = "";
            firstNameTextBox.BorderStyle = BorderStyle.None;
            firstNameTextBox.Clear();
            lastNameUpperLabel.Text = "";
            lastNameTextBox.BorderStyle = BorderStyle.None;
            lastNameTextBox.Clear();
            startButton.Enabled = true;
            clearButton.Enabled = true;
            modelsPath.Clear();

        }

        private void enterToTestingMode(object sender, EventArgs e)
        {
            systemMode = Mode.TESTING_MODE;
            patientIDUpperLabel.Text = "Patient ID";
            idUpperTextBox.BorderStyle = BorderStyle.Fixed3D;
            firstNameUpperLabel.Text = "First Name";
            firstNameTextBox.BorderStyle = BorderStyle.Fixed3D;
            lastNameUpperLabel.Text = "Last Name";
            lastNameTextBox.BorderStyle = BorderStyle.Fixed3D;
            performingTestLabel.Visible = false;
            upperTestNameLabel.Text = "";


        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            fingerTapsLeftTextBox.Clear();
            handMovementsLeftTextBox.Clear();
            fingerTapsRightTextBox.Clear();
            handMovementsRightTextBox.Clear();
        }

        private void fingerTapsTextBox_TextChanged(object sender, EventArgs e)
        {
            trainingGrades.LfingerTaps = fingerTapsLeftTextBox.Text.ToString();
            startButton.Enabled = true;
            clearButton.Enabled = true;
            startKinectButton.Enabled = false;

        }

        private void handMovementsTextBox_TextChanged(object sender, EventArgs e)
        {
            trainingGrades.LhandMovments = handMovementsLeftTextBox.Text.ToString();
            startButton.Enabled = true;
            clearButton.Enabled = true;
            startKinectButton.Enabled = false;
        }

        private void fingerTapsRightTextBox_TextChanged(object sender, EventArgs e)
        {
            trainingGrades.RfingerTaps = fingerTapsRightTextBox.Text.ToString();
            startButton.Enabled = true;
            clearButton.Enabled = true;
            startKinectButton.Enabled = false;
        }

        private void handMovementsRightTextBox_TextChanged(object sender, EventArgs e)
        {
            trainingGrades.RhandMovments = handMovementsRightTextBox.Text.ToString();
            startButton.Enabled = true;
            clearButton.Enabled = true;
            startKinectButton.Enabled = false;
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            if (!CheckInput.isNumber(IDTextBox.Text))
            {
                MessageBox.Show("ID must contains only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!CheckInput.checkScore(handMovementsLeftTextBox.Text) ||
                !CheckInput.checkScore(fingerTapsLeftTextBox.Text) ||
                !CheckInput.checkScore(handMovementsRightTextBox.Text) ||
                !CheckInput.checkScore(fingerTapsRightTextBox.Text))
            {
                MessageBox.Show("Score must be 0-4", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!CheckInput.isEmpty(fingerTapsLeftTextBox.Text))
            {
                testsList.Add(23);
            }

            if (!CheckInput.isEmpty(handMovementsLeftTextBox.Text) )
            {
                testsList.Add(24);
            }
            if (!CheckInput.isEmpty(fingerTapsRightTextBox.Text))
            {
                testsList.Add(23);
            }

            if (!CheckInput.isEmpty(handMovementsRightTextBox.Text))
            {
                testsList.Add(24);
            }

            startButton.Enabled = false;
            clearButton.Enabled = false;
            startKinectButton.Enabled = true;
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {

        }

        private void changeKinectMotorAngleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            kinectMotorTilt kinectMotorTilt;
            kinectMotorTilt = new kinectMotorTilt(kinectController.getKinectSensor());
            kinectMotorTilt.ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (excelManeger != null)
            {
                excelManeger.closeFileMgr();
                excelManeger = null; //free this manager
            }
            Application.Exit();
        }


        private void IDTextBox_TextChanged(object sender, EventArgs e)
        {

        }


        private void createTextFileForAllTestsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string FilePath1 = @"C:\parkinsonTool\rawData\training\finger Taps";
            string FilePath2 = @"C:\parkinsonTool\rawData\training\hand Movements";
            string[] dirNamesArry1 = System.IO.Directory.GetDirectories(FilePath1); //get all the ID Directories
            string[] dirNamesArry2 = System.IO.Directory.GetDirectories(FilePath2); //get all the ID Directories
            string[] subfilesNamesArry1;
            string[] subfilesNamesArry2;

            foreach (string iterator in dirNamesArry1)
            {
                subfilesNamesArry1 = System.IO.Directory.GetFiles(iterator, "*.xlsx"); //get all the names of the excel files
                foreach (string tempfileName in subfilesNamesArry1) //for each excel file do...
                {
                    objectForRead objForRead = new objectForRead();
                    objForRead.centerOfHandListForSaving = new List<CenterOfHandStruct>();
                    objForRead.fingerTipsListForSaving = new List<FingerTipsStruct>();
                    objForRead.path = tempfileName;
                    excelManeger.loadDataFromExcel(ref objForRead); //loads the data from the excel file to the objForRead struct.
                    excelManeger.putDataToText(objForRead, "finger Taps");
                }
            }

            foreach (string iterator in dirNamesArry2)
            {
                subfilesNamesArry2 = System.IO.Directory.GetFiles(iterator, "*.xlsx"); //get all the names of the excel files
                foreach (string tempfileName in subfilesNamesArry2) //for each excel file do...
                {
                    objectForRead objForRead = new objectForRead();
                    objForRead.centerOfHandListForSaving = new List<CenterOfHandStruct>();
                    objForRead.fingerTipsListForSaving = new List<FingerTipsStruct>();
                    objForRead.path = tempfileName;
                    excelManeger.loadDataFromExcel(ref objForRead); //loads the data from the excel file to the objForRead struct.
                    excelManeger.putDataToText(objForRead, "hand Movements");
                }
            }

        }

    

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void clearTestButton_Click(object sender, EventArgs e)
        {
            patientIDTextBox.Clear();
            idUpperTextBox.Clear();
            firstNameTextBox.Clear();
            lastNameTextBox.Clear();
        }

        private void startTestsButton_Click(object sender, EventArgs e)
        {
            if (checkExistingOfModelFiles())
            {
                testsList.Add(23);
                testsList.Add(24);
                testsList.Add(23);
                testsList.Add(24);
                startKinectButton.Enabled = true;
                startTestsButton.Enabled = false;
                clearTestButton.Enabled = false;
            }
            
        }

        private void manageUsersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ManageUsersWindow manageUsers = new ManageUsersWindow();
            manageUsers.ShowDialog();
        }

        private void createTrainAndPredictFilesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            CreateFilesWindow createFilesWindow = new CreateFilesWindow(excelManeger);
            createFilesWindow.ShowDialog();
        }

        private void runSVMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SVMWindow svmWindow = new SVMWindow();
            svmWindow.ShowDialog();
        }

        private void createSVMModelToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            CreateSvmModelWindow svmModelWindow = new CreateSvmModelWindow();
            svmModelWindow.ShowDialog();
        }

        private void analyzeVectorFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
                objForgenerateRandomVectorFile obj1 = new objForgenerateRandomVectorFile();
                VectorOperations.scaleAraysInit(ref obj1);
          
                string FilePath = @"C:\parkinsonTool\rawData\training\finger Taps";
                string[] dirNamesArry = System.IO.Directory.GetDirectories(FilePath); //get all the ID Directories

                string path = @"C:\parkinsonTool\svm\analyze_fingerTaps.csv";

                TextWriter tw = new StreamWriter(path);

                UTF8Encoding utf8 = new UTF8Encoding();
                string fileOutPut;
                string[] subfilesNamesArry;
                List<float> tempVector = new List<float>();

                foreach (string iterator in dirNamesArry) //train text file
                {

                    subfilesNamesArry = System.IO.Directory.GetFiles(iterator, "*.text"); //get all the names of the text files
                    foreach (string tempfileName in subfilesNamesArry) //for each text file do...
                    {
                        VectorOperations.createParamaterVector("finger Taps", tempfileName, ref tempVector, ref obj1);
                        int index = 0;
                        foreach (float it in tempVector)
                        {
                            if (index == 0) //for writing the class 
                            {
                                fileOutPut = it + ",";
                                byte[] encodedBytes = utf8.GetBytes(fileOutPut);
                                tw.Write(utf8.GetString(encodedBytes));
                                index++;
                            }
                            else
                            {
                                fileOutPut = + it + ",";
                                byte[] encodedBytes = utf8.GetBytes(fileOutPut);
                                tw.Write(utf8.GetString(encodedBytes));
                                index++;
                            }
                        }
                        fileOutPut = tempfileName + ",";
                        byte[] encodedBytes1 = utf8.GetBytes(fileOutPut);
                        tw.Write(utf8.GetString(encodedBytes1));
                        
                        
                        tempVector.Clear();
                        tw.WriteLine(" ");

                    } //end of loop

                } //end of loop

                // close the stream
                tw.Close();
            //==============================================================//

                FilePath = @"C:\parkinsonTool\rawData\training\hand Movements";
                dirNamesArry = System.IO.Directory.GetDirectories(FilePath); //get all the ID Directories

                path = @"C:\parkinsonTool\svm\analyze_handMovments.csv";

                tw = new StreamWriter(path);
                utf8 = new UTF8Encoding();
                tempVector.Clear();

                foreach (string iterator in dirNamesArry) //train text file
                {

                    subfilesNamesArry = System.IO.Directory.GetFiles(iterator, "*.text"); //get all the names of the text files
                    foreach (string tempfileName in subfilesNamesArry) //for each text file do...
                    {
                        VectorOperations.createParamaterVector("hand Movements", tempfileName,ref tempVector,ref obj1);
                        int index = 0;
                        foreach (float it in tempVector)
                        {
                            if (index == 0) //for writing the class 
                            {
                                fileOutPut = it + ",";
                                byte[] encodedBytes = utf8.GetBytes(fileOutPut);
                                tw.Write(utf8.GetString(encodedBytes));
                                index++;
                            }
                            else
                            {
                                fileOutPut = +it + ",";
                                byte[] encodedBytes = utf8.GetBytes(fileOutPut);
                                tw.Write(utf8.GetString(encodedBytes));
                                index++;
                            }
                        }
                        fileOutPut = tempfileName + ",";
                        byte[] encodedBytes1 = utf8.GetBytes(fileOutPut);
                        tw.Write(utf8.GetString(encodedBytes1));

                        tempVector.Clear();
                        tw.WriteLine(" ");

                    } //end of loop

                } //end of loop

                // close the stream
                tw.Close();


                MessageBox.Show("Analyze of Vector files finished", "SVM", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        private void patientIDTextBox_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
